﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RPSImporter.Infrastructure;
using RPSImporter.Models.Importers;
using System.Configuration;
using System.IO;
using RPSImporter.Properties;

namespace RPSImporter.Controllers
{
   public class ImportController : BaseController
   {
      //
      // GET: /Import/

      public ActionResult Index()
      {
         return View();
      }

      [HttpPost]
      public ActionResult Upload(HttpPostedFileBase file)
      {
         Util.Result result = new Util.Result();

         if (file != null && Request.Files.Count != 0)
         {
            try
            {
               string saveFilePath = String.Format(@"{0}{1}", ConfigurationManager.AppSettings["ImportPath"], file.FileName);
               if (!Directory.Exists(ConfigurationManager.AppSettings["ImportPath"]))
               {
                  Directory.CreateDirectory(ConfigurationManager.AppSettings["ImportPath"]);
               }
               file.SaveAs(saveFilePath);

               string fileType = Request.Form["supportedFiles"];
               var importer = ImporterFactory.Instance.GetImporter(saveFilePath);
               if (importer != null)
               {
                  if (!importer.Import(fileType))
                  {
                     this.ViewBag.Error = importer.Error;
                  }
                  result.Messages = importer.Messages;
               }
               else
               {
                  result.Messages.Add(Resources.FileTypeUnknown_Text);
               }
            }
            catch (Exception ex)
            {
               result.Messages.Add(ex.Message);
            }
         }
         return View(result);
      }
   }
}
